package com.cn.server.module.login.service;

import com.cn.common.core.exception.ErrorCodeException;
import com.cn.common.core.model.ResultCode;
import com.cn.common.core.session.Session;
import com.cn.common.core.session.SessionManager;
import com.cn.common.core.spi.ChatSpiLoader;
import com.cn.common.module.login.response.LoginResponse;
import com.cn.server.Constant;
import com.cn.server.module.login.ImUser;
import com.cn.server.spi.IMsgCacheSpiDao;
import com.cn.server.spi.IUserSpiDao;
import io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Component;

/**
 */
@Component
public class UserServiceImpl implements UserService {

    private IUserSpiDao iUserSpiDao;
    private IMsgCacheSpiDao iMsgCacheSpiDao;

    public UserServiceImpl() {
        iUserSpiDao = ChatSpiLoader.load(IUserSpiDao.class);
        iMsgCacheSpiDao = ChatSpiLoader.load(IMsgCacheSpiDao.class);
    }

    @Override
    public LoginResponse login(Session session, String loginName, String xToken) {

        // 判断当前会话是否已登录
        if (session.getAttachment() != null) {
            throw new ErrorCodeException(ResultCode.HAS_LOGIN, Constant.HAS_LOGIN);
        }

        // 用户不存在
        ImUser imUser = iUserSpiDao.getImUserByLoginName(loginName);
        if (imUser == null) {
            throw new ErrorCodeException(ResultCode.USER_NO_EXIST, Constant.USER_NO_EXIST);
        }
        String redisToken = iUserSpiDao.getUserTokenByLoginName(loginName);
        // 密码错误
        if (!redisToken.equals(xToken)) {
            throw new ErrorCodeException(ResultCode.TOKEN_ERROR, Constant.TOKEN_ERROR);
        }

        // 判断是否在其他地方登录过
        boolean onlineUser = SessionManager.isOnlineUser(imUser.getLoginName());
        if (onlineUser) {
            Session oldSession = SessionManager.removeSession(imUser.getLoginName());
            oldSession.removeAttachment();
            // 踢下线
            oldSession.close();
        }

        // 加入在线用户会话
        if (SessionManager.putSession(imUser.getLoginName(), session)) {
            session.setAttachment(imUser);
        } else {
            throw new ErrorCodeException(ResultCode.LOGIN_FAIL, Constant.LOGIN_FAIL);
        }
        // 创建Response传输对象返回
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setStatus(ResultCode.SUCCESS);
        String offMsgJson = iMsgCacheSpiDao.getOffLineMsgByLoginName(loginName);
        if (!StringUtil.isNullOrEmpty(offMsgJson)) {
            loginResponse.setJson(offMsgJson);
        }
        return loginResponse;
    }
}
